﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using OpenTK;
using System.Diagnostics;
using System.IO;
using Assimp;
using System.Resources;
using System.Drawing.Drawing2D;
using System.Threading;
using OpenTK.Platform;
using System.Threading.Tasks;

namespace testopenTk
{
    public partial class Form1 : Form
    {
        int FBO = 0;
        public double timeslice = 0;//每帧时间
        double accumulator = 0;//时间
        int idleCounter = 0;//帧数
        public Matrix4 perspective;
        //鼠标位置
        private Point mousepos;
        //视口
        private int[] view = new int[4];
        #region light
        public struct lightingStruct
        {
            public Color4 ambient;
            public Color4 diffuse;
            public Color4 specular;
        }
        public lightingStruct whiteLight = new lightingStruct
        {
            ambient = new Color4(0.2f, 0.2f, 0.2f, 1.0f),
            diffuse = new Color4(1.0f, 1.0f, 1.0f, 1.0f),
            specular = new Color4(1.0f, 1.0f, 1.0f, 1.0f)
        };
        lightingStruct redLight = new lightingStruct
        {
            ambient = new Color4(0.2f, 0.0f, 0.0f, 1.0f),
            diffuse = new Color4(1.0f, 0.0f, 0.0f, 1.0f),
            specular = new Color4(1.0f, 0.0f, 0.0f, 1.0f)
        };
        lightingStruct yellowLight = new lightingStruct
        {
            ambient = new Color4(0.0f, 0.0f, 0.0f, 1.0f),
            diffuse = new Color4(1.0f, 1.0f, 0.0f, 1.0f),
            specular = new Color4(1.0f, 1.0f, 0.0f, 1.0f)
        }; 
        #endregion
        const int lightNum=3;
        public Form1()
        {

            InitializeComponent();
            //this.glControl1 = new OpenTK.GLControl();
            //this.glControl1.BackColor = System.Drawing.Color.Black;
            //this.glControl1.Location = new System.Drawing.Point(12, 3);
            //this.glControl1.Name = "glControl1";
            //this.glControl1.Size = new System.Drawing.Size(374, 247);
            //this.glControl1.TabIndex = 0;
            //this.glControl1.VSync = false;
            //this.glControl1.Load += new System.EventHandler(this.glControl1_Load);
            //this.glControl1.Paint += new System.Windows.Forms.PaintEventHandler(this.glControl1_Paint);
            //this.glControl1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.glControl1_KeyDown);
            //this.glControl1.MouseClick += new System.Windows.Forms.MouseEventHandler(this.glControl1_MouseClick);
            //this.glControl1.Resize += new System.EventHandler(this.glControl1_Resize);
        }
        Stopwatch sw = new Stopwatch(); // available to all event handlers
        private void glControl1_Load(object sender, EventArgs e)
        {
           
            MyMessage.listbox("esc:关闭");
            MyMessage.listbox("wsad:方向");
            MyMessage.listbox("F1:全屏切换");
            MyMessage.listbox("F2:glcontrol充满窗口");
            MyMessage.listbox("F6:信息提示");
            MyMessage.listbox("F12:方向按钮显示/隐藏");
            MyMessage.listbox("v:复制选中模型");
            MyMessage.listbox("T:无边框且透明");
            
            //this.pbx_left.Parent = glControl1;
            //glControl1.Controls.Add(pbx_left);
            //glControl1.Dock = DockStyle.Fill;
            #region Release模式

#if (DEBUG)
#else
            //顺序交换则不遮盖任务栏
            this.FormBorderStyle = FormBorderStyle.None;
            this.WindowState = FormWindowState.Maximized;
            glControl1.Dock = DockStyle.Fill;
            //foreach (Control item in this.Controls)
            //{
            //    if (item.Name == "glControl1")
            //    {
            //        item.Dock = DockStyle.Fill;
            //        continue;
            //    }
            //    item.Visible = false;
            //}
#endif
            #endregion
            Shaderinit();
            SetupViewport();
            Application.Idle += Application_Idle;
            sw.Start(); 
            //初始化
            Shadow.initShadow(Width, Height);
            #region gl设置
            Vector4 t = new Vector4(100, 100, 100, 0);
            GL.Uniform4(Shader.LightPosition, t);
            GL.Enable(EnableCap.Texture2D);
            //启用混合
            //GL.Enable(EnableCap.Texture2D);
            GL.Enable(EnableCap.Blend);
            GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
            //启用深度测试
            GL.Enable(EnableCap.DepthTest);
            GL.ClearDepth(1.0f);
            GL.DepthFunc(DepthFunction.Lequal);
            GL.Enable(EnableCap.LineSmooth);
            GL.Hint(HintTarget.LineSmoothHint, HintMode.Nicest);
            //GL.ShadeModel(ShadingModel.Smooth);
            //GL.Disable(EnableCap.CullFace);
            GL.ClearColor(Color4.Black);
            //GL.Color3(255, 255, 0);
            //解决共面时移动闪烁
            GL.Enable(EnableCap.PolygonOffsetFill);
            #endregion

            #region 添加模型
            //Thread th = new Thread(() =>
            //  {
            //      MyInfo.AssRead();
            //  },102400);
            //th.IsBackground = true;
            //th.Start();
            MyInfo.AssRead();
            #endregion

        }
        void Application_Idle(object sender, EventArgs e)
        {
            
            sw.Stop();
            timeslice = sw.Elapsed.TotalMilliseconds;
            sw.Reset();
            sw.Start();
            idleCounter++;
            accumulator += timeslice;
            if (accumulator > 1000)
            {
                lab_FPS.Text = "FPS:" + idleCounter.ToString();//帧数
                accumulator -= 1000;
                idleCounter = 0; // don't forget to reset the counter!
            }
            float deltaRotation = (float)timeslice / 20.0f;
            glControl1.Invalidate();
        }

        private void glControl1_MouseClick(object sender, MouseEventArgs e)
        {
           
            
        }
        private int InitFrameBufferObj(int width, int height)
        {
            int _FBO = GL.GenFramebuffer();
            int colorBuffer = GL.GenRenderbuffer();
            int depthBuffer = GL.GenRenderbuffer();
            GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, colorBuffer);
            GL.RenderbufferStorage(RenderbufferTarget.Renderbuffer, RenderbufferStorage.Rgb8, width, height);
            GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, depthBuffer);
            GL.RenderbufferStorage(RenderbufferTarget.Renderbuffer, RenderbufferStorage.DepthComponent16, width, height);
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, FBO);
            GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0,
               RenderbufferTarget.Renderbuffer, colorBuffer);
            GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, FramebufferAttachment.DepthAttachment,
               RenderbufferTarget.Renderbuffer, depthBuffer);
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
            return _FBO;
        }
        private void Shaderinit()
        {
           
            //pictureBox1.Image = new Bitmap("Res/071649145195388.jpg");
            Shader.SProgram = Shader.InitShader("vShader.glsl", "fShader.glsl");
            if (Shader.SProgram == 0)
            {
                MyMessage.show("Shader无法加载");
                this.Close();
            }
            GL.UseProgram(Shader.SProgram);

            Shader.vPosition = GL.GetAttribLocation(Shader.SProgram, "vPosition");
            Shader.vTexCoord = GL.GetAttribLocation(Shader.SProgram, "vTexCoord");
            Shader.vNormal = GL.GetAttribLocation(Shader.SProgram, "vNormal");

            Shader.ModelView = GL.GetUniformLocation(Shader.SProgram, "ModelView");
            Shader.Projection = GL.GetUniformLocation(Shader.SProgram, "Projection");

            
            Shader.bOnlyColor = GL.GetUniformLocation(Shader.SProgram, "bOnlyColor");
            Shader.SelectColor = GL.GetUniformLocation(Shader.SProgram, "SelectColor");
            
            //Shader.Camera = GL.GetUniformLocation(Shader.SProgram, "Camera");
            Shader.AmbientProduct = GL.GetUniformLocation(Shader.SProgram, "AmbientProduct");
            Shader.DiffuseProduct = GL.GetUniformLocation(Shader.SProgram, "DiffuseProduct");
            Shader.SpecularProduct = GL.GetUniformLocation(Shader.SProgram, "SpecularProduct");
            Shader.Shininess = GL.GetUniformLocation(Shader.SProgram, "Shininess");
            Shader.Emission = GL.GetUniformLocation(Shader.SProgram, "Emission");
            GL.Uniform1(GL.GetUniformLocation(Shader.SProgram, "tex"), 0);

            Shader.bOnlyTexture = GL.GetUniformLocation(Shader.SProgram, "bOnlyTexture");
            Shader.LightPosition = GL.GetUniformLocation(Shader.SProgram, "LightPosition");
            Shader.bOnlyShadow = GL.GetUniformLocation(Shader.SProgram, "bOnlyShadow");

            Shader.LightOn = GL.GetUniformLocation(Shader.SProgram, "LightOn");
            //float[] temp = { 0.0f, 5.0f, 0.0f, 1.0f };
            GL.Uniform4(Shader.LightPosition + 2,new Vector4(0.0f, 0.0f, 0.0f, 1.0f));
            GL.Uniform3(GL.GetUniformLocation(Shader.SProgram, "SpotDirection"),
               1, 0, 0);
            GL.Uniform1(GL.GetUniformLocation(Shader.SProgram, "SpotCutOff"), 8);
            GL.Uniform1(GL.GetUniformLocation(Shader.SProgram, "SpotExponent"), 3);
            for (int i = 1; i < lightNum; i++)
            {
                GL.Uniform1(Shader.LightOn+i ,0);
            }
            GL.Uniform1(Shader.LightOn , 1);
        }
        private void SetupViewport()
        {
            int w = glControl1.Width;
            int h = glControl1.Height;
            GL.Viewport(glControl1.ClientRectangle); // Use all of the glControl painting area
            //GL.MatrixMode(MatrixMode.Projection);
            //perspective =/* Matrix4.CreateOrthographicOffCenter(-1,1,-0.8f,0.8f,0,64);*/
            //Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, w / (float)h, 0.1f, 64);
            //perspective = Matrix4.CreateTranslation(0, 0, -3) * perspective;

            //if (Shader.Projection != 0)
            //    GL.UniformMatrix4(Shader.Projection, false, ref perspective);
            Camera.SetCamera(w, h);
            if (FBO != 0)
            {
                GL.DeleteFramebuffer(FBO);
            }
            FBO= InitFrameBufferObj(w, h);
        }
        //static  Bitmap bm = new Bitmap(472, 296);
        //IntPtr bitblt = bm.GetHbitmap();
        private void MainDraw(bool select)
        {
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
            //MyMessage.TimeStart();
            SpriteList.Draw(select, timeslice,Camera.MainCamera,num_layer.Value); 
            //MyMessage.TimeStopAndShow();
        }
        //Bitmap myimage = new Bitmap("Res/1371714170_1812223777.gif");
        private void glControl1_Paint(object sender, PaintEventArgs e)
        {
            Camera.UpdateCamera((float)timeslice);
            Camera.collision = false;
            SpriteList.CollisionTest();
            //e.Graphics.DrawImage(myimage, 0, 0);
            //e.Graphics.
            //Shadow.bindforwirting();
            //GL.Uniform1(Shader.bOnlyShadow, 1);
            //MainDraw(false);
            //GL.Uniform1(Shader.bOnlyShadow, 0);
            //Shadow.BindForReading(TextureUnit.Texture0);
            //pictureBox1.BackgroundImage = GrabScreenshot(Width, Height, this.ClientRectangle, Shadow.FBO);
            //GL.PushAttrib(AttribMask.ViewportBit);
            //GL.Viewport(0, 0, 11, 11);
            //GL.PopAttrib();
            ////线框模式
            //GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line);

            ////渲染到纹理
            //GL.BindTexture(TextureTarget.Texture2D, 1);
            //GL.CopyTexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, 0, 0, 512, 512);
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
            #region FBO_To_Screen
            //GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, FBO);
            //GL.BindFramebuffer(FramebufferTarget.DrawFramebuffer, 0);

            //GL.BlitFramebuffer(0, 0, glControl1.Width, glControl1.Height, 0, 0, glControl1.Width, glControl1.Height,
            //                         ClearBufferMask.ColorBufferBit, BlitFramebufferFilter.Linear);

            //GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, 0);
            //GL.BindFramebuffer(FramebufferTarget.DrawFramebuffer, 0);
            #endregion
           
            MainDraw(false);

            //glControl1.WindowInfo.Handle;
            GraphicsContext.CurrentContext.SwapBuffers();
            //glControl1.SwapBuffers();
            //glControl1.Context.SwapBuffers();
            //glControl1.PerformContextUpdate();
            //pbx_left.BackgroundImage = (Bitmap)glControl1.BackgroundImage;
            //Bitmap bmp = glControl1.GrabScreenshot();
            //pbx_left.BackgroundImage = glControl1.GrabScreenshot();
            //GL.TexBuffer
            //GL.BindTexture(TextureTarget.Texture2D, 1);
            ////GL.CopyTexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, 0, 0, 512, 512);
            //GL.CopyTexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgb, 0, 0, 512, 512, 0);
            ////GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, 512, 512,PixelFormat.Rgb,PixelType.Bitmap,IntPtr.Zero);
    
        }
        private void MyDraw(bool select)
        {
          
        }
       
        private void glControl1_Resize(object sender, EventArgs e)
        {
            SetupViewport();
            button_left.Size = new Size(glControl1.Size.Width / 6, glControl1.Height / 6);
            button_left.Location = new Point(glControl1.Location.X, glControl1.Height / 2 - button_left.Height / 2);
            button_right.Size = new Size(glControl1.Size.Width / 6, glControl1.Height / 6);
            button_right.Location = new Point(glControl1.Width-button_right.Width, glControl1.Height / 2 - button_left.Height / 2);
            button_up.Size = new Size(glControl1.Width / 8, glControl1.Height / 8);
            button_up.Location = new Point(glControl1.Width / 2 - button_up.Width / 2, glControl1.Location.Y);
            button_down.Size= new Size(glControl1.Width / 8, glControl1.Height / 8);
            button_down.Location = new Point(glControl1.Width / 2 - button_up.Width / 2, glControl1.Height-button_down.Height);
            lab_info.Location = new Point(glControl1.Width / 2 - lab_info.Width / 2, glControl1.Height /4);
            glControl1.Invalidate();
        }
        private void numericUpDown3_ValueChanged(object sender, EventArgs e)
        {
          

        }
        bool test = false;

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            SpriteList.DisposeResoure();
            GL.DeleteFramebuffer(FBO);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MyInfo.Read();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
            
        }
        bool click = false;
        private void glControl1_MouseDown(object sender, MouseEventArgs e)
        {
            click = true;
            Sprite3D temp;
            mousepos = e.Location;
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, FBO);
            if (FramebufferErrorCode.FramebufferComplete == GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer))
            {
                MainDraw(true);
            }
            else
            {
                MyMessage.show("FBO_error:" + GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer).ToString());
            }

            GL.ReadPixels(e.X, glControl1.Height - e.Y, 1, 1,
                PixelFormat.Rgb, PixelType.UnsignedByte, read);
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
            if (e.Button == MouseButtons.Left)
            {
                //Properties.Resources.button_left
                temp = SpriteList.Touch(ColorToNameIndex(new Color4(read[0], read[1], read[2], 1)));
                //MyMessage.lable4Show(read[0].ToString() + " "
                //    + read[1].ToString() + " " + read[2].ToString() + Environment.NewLine
                //    + ColorToNameIndex(new Color4(read[0], read[1], read[2], 1)).ToString());
                if (temp != null)
                {
                    foreach (Sprite3D t in SpriteList.sprite3Dlist)
                    {
                        t.touch = false;
                    }
                    temp.touch = true;
                    MyMessage.lable5Show(temp.name);
                }
                else
                {
                    MyMessage.lable5Show("no touch");
                }
            }
            if (e.Button == MouseButtons.Right)
                test = !test;
            
        }

        private void glControl1_MouseUp(object sender, MouseEventArgs e)
        {
            click = false;
            mousepos = e.Location;
        }
        Byte[] read = new Byte[3];

        private void SaveAll_Click(object sender, EventArgs e)
        {
            MyInfo.Save(SpriteList.sprite3Dlist);
        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            //SpriteList.sprite3Dlist.Clear();
            //openFileDialog1.InitialDirectory = Application.StartupPath;
            //string s = openFileDialog1.FileName.Replace(Application.StartupPath+"\\", "");
            //MyMessage.lable4Show(s);
            //SpriteList.sprite3Dlist.Add(new Sprite3D(s));
            //AssLoad al = new AssLoad(s);
        }

        private void btn_Delete_Click(object sender, EventArgs e)
        {
            SpriteList.DeleteTouch();
        }
        float rotaTemp;
        private void glControl1_MouseMove(object sender, MouseEventArgs e)
        {
            if (click)
            {
                rotaTemp += (mousepos.Y - e.Location.Y)/2;
                if (rotaTemp>100)
                {
                    rotaTemp = 100;
                }
                if (rotaTemp<-160)
                {
                    rotaTemp = -160;
                }
                Camera.Rota_Y = Matrix4.CreateRotationX(rotaTemp/360);
            }
            mousepos = e.Location;
            //GL.BindFramebuffer(FramebufferTarget.Framebuffer, FBO);
            //GL.ReadPixels(e.X, glControl1.Height - e.Y, 1, 1,
            //   PixelFormat.Rgb, PixelType.UnsignedByte, read);
            //GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);

        }
        int ColorToNameIndex(Color4 color)
        {
            return (int)((color.R + color.G * 256 + color.B * 256 * 256) * 255);
        }
        public static Bitmap BytesToBitmap(byte[] Bytes)
        {
            MemoryStream stream = null;
            try
            {
                stream = new MemoryStream(Bytes);
                return new Bitmap((Image)new Bitmap(stream));
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
            catch (ArgumentException ex)
            {
                throw ex;
            }
            finally
            {
                stream.Close();
            }
        }
        /// <summary>
        /// 截图功能
        /// </summary>
        /// <param name="w">宽度</param>
        /// <param name="h">高度</param>
        /// <param name="rec">矩形工作区域</param>
        /// <returns></returns>
        public Bitmap GrabScreenshot(int w,int h,Rectangle rec,int fbo)
        {
            if (GraphicsContext.CurrentContext == null)
                throw new GraphicsContextMissingException();
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, fbo);
            //GL.BindTexture(TextureTarget.Texture2D, fbo);
            Bitmap bmp = new Bitmap(w, h);
            System.Drawing.Imaging.BitmapData data =
                bmp.LockBits(rec, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            GL.ReadPixels(0, 0, w, h, PixelFormat.Bgr, PixelType.UnsignedByte, data.Scan0);

            bmp.UnlockBits(data);

            bmp.RotateFlip(RotateFlipType.RotateNoneFlipY);
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
            return bmp;
        }

        private void glControl1_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Space:
                    Camera.Y_Up = true;
                    break;
                case Keys.Z:
                    MyInfo.printToTexture(3, "12312312312312");
                    break;
                case Keys.Escape:
                    Close();
                    break;
                case Keys.W:
                    Camera.Up = true;
                    break;
                case Keys.S:
                    Camera.Down = true;
                    break;
                case Keys.A:
                    
                    Camera.Left = true;
                    break;
                case Keys.D:
                    Camera.Right = true;
                    break;
                case Keys.T:
                    if (FormBorderStyle == FormBorderStyle.Sizable
                        && this.TransparencyKey==Color.Empty)
                    {
                        FormBorderStyle = FormBorderStyle.None;
                        this.TransparencyKey = Color.Black;
                    }
                    else if (FormBorderStyle == FormBorderStyle.None
                        && this.TransparencyKey == Color.Black)
                    {
                        this.TransparencyKey = Color.Empty;
                        FormBorderStyle = FormBorderStyle.Sizable;
                    }
                    break;
                case Keys.F6:
                    lab_info.Visible = !lab_info.Visible;
                    //lab_FPS.Visible = true;
                    break;
                case Keys.F12:
                    button_down.Visible = !button_down.Visible;
                    button_left.Visible = !button_left.Visible;
                    button_up.Visible = !button_up.Visible;
                    button_right.Visible = !button_right.Visible;
                    break;
                case Keys.F2:
                    if (glControl1.Dock == DockStyle.Fill)
                    {
                        glControl1.Dock = DockStyle.None;
                    }
                    else if (glControl1.Dock == DockStyle.None)
                    {
                        glControl1.Dock = DockStyle.Fill;
                    }

                    break;
                case Keys.F1:
                    if (FormBorderStyle==FormBorderStyle.None
                        &&WindowState==FormWindowState.Maximized)
                    {
                        this.FormBorderStyle = FormBorderStyle.Sizable; ;
                        this.WindowState = FormWindowState.Normal;
                    }
                    else if (FormBorderStyle == FormBorderStyle.Sizable
                       && WindowState == FormWindowState.Normal)
                    {
                        this.FormBorderStyle = FormBorderStyle.None; ;
                        this.WindowState = FormWindowState.Maximized;
                    }
                    break;
                case  Keys.V:
                    Sprite3D lit=null;
                    foreach (Sprite3D t in SpriteList.sprite3Dlist)
                    {
                        if (t.touch)
                        {
                            lit = t;
                            t.touch = false;
                            t.si.Visible = true;
                        }
                    }
                    if (lit!=null)
                    {
                        Sprite3D theNew = new Sprite3D(lit.spath, lit.AssDraw);
                        SpriteList.sprite3Dlist.Add(theNew);
                        theNew.si.num_layer.Value = lit.si.num_layer.Value;
                        theNew.si.num_Animation.Value = lit.si.num_Animation.Value;
                        theNew.si.Location_X.Value = lit.si.Location_X.Value;
                        theNew.si.Location_Y.Value = lit.si.Location_Y.Value;
                        theNew.si.Location_Z.Value = lit.si.Location_Z.Value;
                    }
                  
                    break;
                default:
                    break;
            }
        }

        private void glControl1_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Space:
                    Camera.Y_Up = false;
                    break;
                case Keys.W:
                    Camera.Up = false;
                    break;
                case Keys.S:
                    Camera.Down = false;
                    break;
                case Keys.A:
                    Camera.Left = false;
                    break;
                case Keys.D:
                    Camera.Right = false;
                    break;
                case Keys.Delete:
                    SpriteList.DeleteTouch();
                    break;
                default:
                    break;
            }
          
        }

        private void btn_load_Click(object sender, EventArgs e)
        {
            openFileDialog2.ShowDialog();
        }

        private void openFileDialog2_FileOk(object sender, CancelEventArgs e)
        {
            foreach (string s in openFileDialog2.FileNames)
            {
                MyInfo.OneLoad(s.Replace(Application.StartupPath + "\\", ""));
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            SpriteList.DeleteAll();
        }

        private void btn_ARead_Click(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback((object ii) =>
            {
                MyInfo.AssRead();
            }));
        }

        private void btn_ASave_Click(object sender, EventArgs e)
        {
            MyInfo.AssSave(SpriteList.sprite3Dlist);
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {
            Panel temp= ((Panel)(sender));
            temp.Cursor = Cursors.Hand;
            Bitmap bmpBob = new Bitmap(temp.BackgroundImage, temp.Size);
            GraphicsPath graphicsPath = CalculateControlGraphicsPath(bmpBob);
            temp.Region = new Region(graphicsPath);
        }
        /// <summary>
        /// 计算图片的覆盖区域，并以此作为不规则控件的新区域
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        private static GraphicsPath CalculateControlGraphicsPath(Bitmap bitmap)
        {

            GraphicsPath graphicsPath = new GraphicsPath();

            Color colorTransparent = bitmap.GetPixel(0,0);

            int colOpaquePixel = 0;

            for (int row = 0; row < bitmap.Height; row++)
            {

                colOpaquePixel = 0;

                for (int col = 0; col < bitmap.Width; col++)
                {
                    Color t = bitmap.GetPixel(col, row);
                    if ( t!= colorTransparent)
                    {

                        colOpaquePixel = col;

                        int colNext = col;

                        for (colNext = colOpaquePixel; colNext < bitmap.Width; colNext++)
                            if (bitmap.GetPixel(colNext, row) == colorTransparent)
                                break;

                        graphicsPath.AddRectangle(new Rectangle(colOpaquePixel,
                         row, colNext - colOpaquePixel, 1));

                        col = colNext;
                    }
                }
            }

            return graphicsPath;
        }

        private void panel3_MouseDown(object sender, MouseEventArgs e)
        {
            MyMessage.LabInfo("点击选中场景中的物品可详细观看");
            Panel temp= (Panel)sender;
            //MyMessage.listbox(temp.Name);
            switch (temp.Name)
            {
                case "button_left":
                    Camera.Left = true;
                    break;
                case "button_right":
                    Camera.Right = true;
                    break;
                case "button_up":
                    Camera.Up = true;
                    break;
                case "button_down":
                    Camera.Down = true;
                    break;
                default:
                    break;
            }
        }

        private void panel3_MouseUp(object sender, MouseEventArgs e)
        {
            Panel temp = (Panel)sender;
            switch (temp.Name)
            {
                case "button_left":
                    Camera.Left = false;
                    break;
                case "button_right":
                    Camera.Right = false;
                    break;
                case "button_up":
                    Camera.Up = false;
                    break;
                case "button_down":
                    Camera.Down = false;
                    break;
                default:
                    break;
            }
        }

        private void lab_info_MouseClick(object sender, MouseEventArgs e)
        {
            ((Label)sender).Visible = false;
        }

        private void num_layer_ValueChanged(object sender, EventArgs e)
        {
            foreach (Sprite3D t in SpriteList.sprite3Dlist)
            {
                t.touch = false;
            }
        }
    }
}
